#!/bin/sh

# Installation prefix
prefix="%OPTWARE_TARGET_PREFIX%"

# Data directory
PGDATA="$prefix/var/pgsql/data"
PG_DUMP_DIR="$prefix/var/pgsql/8.2/dump"

# Who to run the postmaster as, usually "postgres".  (NOT "root")
PGUSER=postgres

# Where to keep a log file
PGLOG="$PGDATA/serverlog"

# What to use to shut down the postmaster
PGCTL="$prefix/bin/pg_ctl"

# What to use to start up the postmaster (we do NOT use pg_ctl for this,
# as it adds no value and can cause the postmaster to misrecognize a stale
# lock file)
DAEMON="$prefix/bin/postmaster"

#########
if [ -z "$1" ] ; then
    case `echo "$0" | /bin/sed 's:^.*/\(.*\):\1:g'` in
        S??*) rc="start" ;;
        K??*) rc="stop" ;;
        *) rc="usage" ;;
    esac
else
    rc="$1"
fi

case "$rc" in
    start)
	echo -n "Starting PostgreSQL: "
	%OPTWARE_TARGET_PREFIX%/bin/coreutils-su - $PGUSER -c "$DAEMON -D '$PGDATA' &" >>$PGLOG 2>&1
	echo ok
        ;;
    stop)
	echo -n "Stopping PostgreSQL: "
	%OPTWARE_TARGET_PREFIX%/bin/coreutils-su - $PGUSER -c "$PGCTL stop -D '$PGDATA' -s -m fast"
	echo ok
        ;;
    restart)
        "$0" stop
        sleep 1
        "$0" start
        ;;
    dumpall)
        PG_DUMP_FILE=$PG_DUMP_DIR/dumpall-`date +%FT%H%M%S`
        if [ -x $prefix/bin/gzip ]; then
            PG_DUMP_FILE=$PG_DUMP_FILE.gz
            echo -n "PostgreSQL pg_dumpall and gzip to $PG_DUMP_FILE "
            %OPTWARE_TARGET_PREFIX%/bin/coreutils-su - $PGUSER -c "$prefix/bin/pg_dumpall | $prefix/bin/gzip -c > $PG_DUMP_FILE"
        else
            echo -n "PostgreSQL pg_dumpall to $PG_DUMP_FILE "
            %OPTWARE_TARGET_PREFIX%/bin/coreutils-su - $PGUSER -c "$prefix/bin/pg_dumpall > $PG_DUMP_FILE"
        fi
	echo ok
        ;;
    *)  
        echo "Usage: $0 (start|stop|restart|dumpall|usage)"
        ;;
esac
